<template>
  <div class="blogrollIndex" id="blogrollIndex">
    <div class="head-box">
      <div>
        <a-button type="primary" class="addButton" :disabled="!btnPerm.includes('creatAble')" @click="addGroupingRecord">新建链接</a-button>
      <span style="margin-left: 24px;">当前分组： {{ route.query.name }}</span>
      </div>
      <!-- 搜索部分 -->
      <div class="searchContainer">
        <div class="statusSelect">
        是否显示：
        <a-select style="width: 92px;" v-model:value="isEnableValue" @change="statusChange" :options="statusOptions"></a-select>
      </div>
      <div class="searchContent">
        <a-input v-model:value="searchValue" @pressEnter="fetchSysLinkPage" @blur="fetchSysLinkPage" placeholder="搜索链接名称" style="width: 192px;height: 32px" allowClear>
          <template #suffix>
            <i class="iconfont icon-search" @click="fetchSysLinkPage"></i>
          </template>
        </a-input>
      </div>
      </div>
    </div>
    <treeTable :columns="columns.blogrollColumns" :dataSource="resData.records" :isSelect="true" :scroll="scroll"
      ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete" :total="resData.total"
      @changePage="changePage" class="treeTableBox">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'isEnable'">
          <a-switch size="small" v-model:checked="record.isEnable" @change="enableChange($event, record.id)" />
          <span style="margin-left: 8px">
            {{ record.isEnable ? "是" : "否" }}
          </span>
        </template>

        <template v-if="column.dataIndex === 'linkLogoUrl'">
          <!-- <img class="tp" :src="record.linkLogoUrl" alt="" srcset="" /> -->
          <div class="tabletypeImgBox" v-if="record.linkLogoUrl">
            <a-image :src="record.linkLogoUrl" :preview="{ visible: false }" @click="visible = true"
              class="tabletypeImg" />
            <div style="display: none">
              <a-image-preview-group :preview="{
                visible,
                onVisibleChange: (vis: any) => (visible = vis),
              }" class="opppqwq">
                <a-image :src="record.linkLogoUrl" />
              </a-image-preview-group>
            </div>
          </div>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="editRecords(record.id)">编辑</a>
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('moveAble') }" @click="moveRecords([record.id])">移动</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')" @confirm="confirmDelete([record.id])">
            <template #title>
              <p style="width: 197px">是否删除此内容</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
        <a-button :style="{ 'margin-left': '8px' }" @click="moveRecords(rowSelection)"
          :disabled="!rowSelection.length || !btnPerm.includes('moveAble')">移动</a-button>
      </template>
    </treeTable>
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      :cancleText="'关闭'" @handleCancle="handleCancle" @handleOk="handleOk" class="addCorrelation">
      <template v-slot:body>
        <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
          ref="columnFrom">
          <div v-if="isMove">
            <a-form-item label="选择分组" name="linkTypeId" :rules="[{ required: true, trigger: 'blur', message: '请选择分组!' }]">
              <a-select v-model:value="formState.linkTypeId" :options="typeOptions"></a-select>
            </a-form-item>
          </div>
          <div v-else>
            <a-form-item label="ID" name="id" v-if="formState.id">
              <span>{{ formState.id }}</span>
            </a-form-item>
            <a-form-item label="所属分组" name="linkTypeName" v-if="formState.id">
              <span>{{ formState.linkTypeName }}</span>
            </a-form-item>
            <a-form-item label="链接名称" name="linkName" :rules="[{ required: true, trigger: 'blur', message: '请输入链接名称!' }]">
              <a-input v-model:value="formState.linkName" placeholder="请输入链接名称!"></a-input>
            </a-form-item>
            <a-form-item label="URL地址" name="linkUrl"
              :rules="[{ required: true, trigger: 'blur', message: '请输入URL地址!' }]">
              <a-input v-model:value="formState.linkUrl" placeholder="请输入链接地址!"></a-input>
            </a-form-item>
            <a-form-item label="链接图片" name="linkLogoUrl">
              <upload :fileList="uploadList" @uploadFinished="uploadFinished"
                @upload_remove_Finished="upload_remove_Finished" :isAutoUpload="true" :title="'点击上传图片'"></upload>
            </a-form-item>

            <a-form-item label="是否显示" name="typeName">
              <a-switch size="small" v-model:checked="formState.isEnable" />
              <!-- <span style="margin-left: 8px">{{ formState.isEnable ? "是" : "否" }}</span> -->
            </a-form-item>
          </div>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed, watch } from "vue";
import treeTable from "@/components/table/baseTable.vue";
import upload from "@/components/upload/uploadFile.vue";
import columns from "@/components/table/tableConfig/tableColumn/configTableColumn";
import baseModal from "@/components/modal/baseModal.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { scrollType, configDataType } from "@/type.d";
import { getTableScroll, inintDrag } from "@/components/table/tableConfig/table";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { useRoute, useRouter } from "vue-router";
import {routerPerm} from '@/utils/common';
const btnPerm = ref<any[]>([]);
interface dataSourceType {
  [propName: string | number]: any;
}
const route: any = useRoute();
const columnFrom = ref<any>("columnFrom");
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const isVisible = ref<boolean>(false);
const isMove = ref<boolean>(false);
const tagBaseTables = ref<any>(null);
const uploadList = ref<dataSourceType[]>([]);
const typeOptions = ref<dataSourceType[]>([]);

const searchValue = ref<any>(null);
const isEnableValue = ref<any>(null);
const statusOptions = [{ label: "全部", value: null },  { label: "是", value: true },{ label: "否", value: false }];
const dragEnd = ref<any>({});
const visible = ref<boolean>(false);
let rowSelection = ref<(string | number)[]>([]);
let resData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let scroll: scrollType = reactive({ y: "", isFixed: false });
const modAlProps = reactive<dataSourceType>({
  width: "M",
  title: "新建链接",
});
let datas = reactive<dataSourceType>({});
let buttons = ref<dataSourceType[]>([
  //   {
  //     text: "保存并继续新建",
  //     cz: "bcandxj",
  //     keepAlive: true,
  //   },
  {
    text: "保存",
    cz: "bc",
    keepAlive: true,
  },
]);

const formState = ref<dataSourceType>({
  typeName: "",
});

watch(
  () => dragEnd.value,
  (newVal, oldVal) => {
    if (newVal.id && newVal.id != newVal.toId) {
      request
        .fetchSysLinkSort(newVal)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          fetchSysLinkPage();
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    }
  },
  { deep: true }
);
//computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});

const statusChange = () => {
  fetchSysLinkPage();
};
const fetchSysLinkPage = async () => {
  const params = {
    pageNumber: datas.pageNumber || 1,
    pageSize: datas.pageSize || 10,
    linkTypeId: route.query.id,
    linkName: searchValue.value,
    isEnable: isEnableValue.value,
  }
  const data = await request.fetchSysLinkPage(params);
  resData.total = data.total;
  resData.records = data.records.length && data.records.map((item: any, index: number) => {
    item.sortNum = index + 1
    return item
  })
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "blogrollIndex");
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
    dragEnd.value = {};
    setTimeout(() => {
      inintDrag("blogrollIndex", resData, "records", dragEnd);
    }, 40);
  });
};
const fetchSysLinkTypeList = async (datas: dataSourceType = {}) => {
  const data = await request.fetchSysLinkTypeList();
  typeOptions.value = data?.map((item: any) => {
    let obj: dataSourceType = {}
    if (item.id === Number(route.query.id)) {
      obj = {
        value: item.id,
        label: item.name,
        disabled: true
      }
    } else {
      obj = {
        value: item.id,
        label: item.name,
      }
    }
    return obj;
  });
};

const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  fetchSysLinkPage();
};
// 上传图片返回值
const uploadFinished = (data: any) => {
  console.log(data, "data");
  formState.value.linkLogoUrl = data[0].url;
  formState.value.linkLogoId = data[0].id;
  uploadList.value.push({ id: data[0].id, url: data[0].url });
};

// 删除图片
const upload_remove_Finished = (data: any) => {
  setTimeout(() => {
    formState.value.linkLogoUrl = "";
    formState.value.linkLogoId = null;
    uploadList.value = [];
  }, 10);
};

// 添加分组
const addGroupingRecord = () => {
  formState.value = {
    id: null,
    isEnable: true,
    linkLogoId: null,
    linkLogoUrl: "",
    linkName: "",
    linkTypeId: route.query.id,
    linkUrl: "",
  };
  uploadList.value = [];
  modAlProps.title = '新建链接'
  buttons.value = [
    {
      text: "保存并继续新建",
      cz: "bcandxj",
      keepAlive: true,
    },
    {
      text: "保存",
      cz: "bc",
      keepAlive: true,
    },
  ];
  isMove.value = false;
  isVisible.value = true;
};
// 编辑
const editRecords = async (id: any) => {
  if(!btnPerm.value.includes('editAble')) return
  isMove.value = false;
  isVisible.value = true;
  modAlProps.title = '编辑链接'
  buttons.value = [
    {
      text: "保存",
      cz: "bc",
      keepAlive: true,
    },
  ];
  const data = await request.fetchSysLinkDetail({ id: id });
  formState.value = {
    isEnable: data.isEnable,
    id: data.id,
    linkLogoUrl: data.linkLogoUrl,
    linkLogoId: data.linkLogoId,
    linkName: data.linkName,
    linkTypeName: data.linkTypeName,
    linkUrl: data.linkUrl,
    linkTypeId: route.query.id,
  };
  nextTick(() => {
    uploadList.value = [];
    if (data.linkLogoId && data.linkLogoUrl) {
      uploadList.value.push({ id: data.linkLogoId, url: data.linkLogoUrl });
    }
  });
};

const handleOk = async (msg: dataSourceType) => {
  columnFrom.value
    .validate()
    .then(() => {
      if (isMove.value) {
        request
          .fetchSysLinkMove(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchSysLinkPage();
              isVisible.value = false;
              formState.value = {};
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else if (formState.value.id) {
        request
          .fetchSysLinkUpdate(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchSysLinkPage();
              isVisible.value = false;
              formState.value = {};
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        request
          .fetchSysLink(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchSysLinkPage();
              if (msg.cz == "bc") {
                isVisible.value = false;
              }
              formState.value = {
                id: null,
                isEnable: true,
                linkLogoId: null,
                linkLogoUrl: "",
                linkName: "",
                linkTypeId: route.query.id,
                linkUrl: "",
              };
              uploadList.value = [];
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }
    })
    .catch(() => { });
};
const handleCancle = async (msg: dataSourceType) => {
  isVisible.value = false;
};

// 友情链接
const moveRecords = async (item: any) => {
  if(!btnPerm.value.includes('moveAble')) return
  isMove.value = true;
  isVisible.value = true;
  modAlProps.title = '移动分组'
  formState.value = {
    ids: item,
    linkTypeId: "",
  };
  fetchSysLinkTypeList();
};
// 停用启用
const enableChange = async (e: any, item: any) => {
  if (e) {
    request
      .fetchSysLinkEnable({ id: item })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          fetchSysLinkPage();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else {
    request
      .fetchSysLinkDisable({ id: item })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          fetchSysLinkPage();
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  }
};
// 删除
const confirmDelete = async (datas: any) => {
  request
    .fetchSysLinkDelete({ ids: datas })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchSysLinkPage();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

// 删除多个
const deleteSelectedAll = async (item: any) => {
  Modal.confirm({
    content: "您确定删除选中的内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      confirmDelete(tagBaseTables.value.selectedRowKeys);
    },
    onCancel() { },
  });
};
onMounted(() => {
  btnPerm.value = routerPerm()
  fetchSysLinkPage();
});
</script>

<style lang="less" scoped>
.blogrollIndex {
  background-color: #fff;
  padding: 24px;
  height: calc(100% - 84px);

  //   overflow: hidden;
  //   display: flex;
  //   flex-direction: column;
  .head-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    .searchContainer {
      display: flex;
      .statusSelect {
        width: 168px;
        font-size: 14px;
        margin-right: 13px;
      }
    }
  }

  .tabletypeImgBox {
    // max-height: 40px;
    max-width: 80px;

    max-height: 80px;
    // padding: 8px;
    background: #ffffff;
    border-radius: 2px;
    // border: 1px solid rgba(0, 0, 0, 0.15);
  }

  .tabletypeImg {
    width: 40px;
    width: auto;
    height: 40px;

    height: auto;
    margin: auto;
    //   width: 16px;
    //   height: 16px;
    // line-height: 18px;
  }

  ::v-deep(.ant-table-body) {
    cursor: move;
  }

  ::v-deep(.ant-table-cell) {
    vertical-align: middle;
  }


  .eidtRecords {
    margin-right: 16px;
  }
}

:deep(.ant-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.ant-form-item-label) {
  width: 80px;
}
</style>
<style lang="less">
.ant-image-preview-img-wrapper {

  // left: 50%;
  // transform: translateX(-50%);
  img {
    display: inline-block;
  }
}
</style>
